package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.mapper.ApCollectionBehaviorMapper;
import com.heima.article.service.ApCollectionBehaviorService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionBehaviorServiceImpl extends ServiceImpl<ApCollectionBehaviorMapper , ApCollection> implements ApCollectionBehaviorService {
    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if (dto == null && dto.getEntryId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getEntryId, apBehaviorEntry.getId()).eq(ApCollection::getArticleId, dto.getEntryId()));
        if (apCollection == null && dto.getOperation() == 0){
            apCollection = new ApCollection();
            apCollection.setCollectionTime(new Date());
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setType((short)0);
            apCollection.setOperation(dto.getOperation());
            apCollection.setPublishedTime(dto.getPublished_Time());
            save(apCollection);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            apCollection.setOperation(dto.getOperation());
            updateById(apCollection);
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
